import { defineStore } from 'pinia'
import { ref } from 'vue'
import { loginAPI } from '@/api/login'
import {useCartStore} from './cart'
import { mergeCartAPI,getCartAPI } from '@/api/cart'
export const useUserStore = defineStore('user', () => {
    const cartStore = useCartStore()
  const userInfo = ref({})
  const getUserInfo = async ({ account, password }) => {
    const res = await loginAPI({ account, password })
    userInfo.value = res
    // 合并购物车
    await mergeCartAPI(cartStore.cartList.map( item => {
      return {
        skuId:item.skuId,
        selectd:item.selectd,
        count:item.count
      }
    }))
    // 更新数据
    const result = await getCartAPI()
    useCartStore.cartList.value = result
  }
   // 退出时清除用户信息
   const clearUserInfo = () => {
    userInfo.value = {}
    cartStore.clearCart()

  }
  return {
    userInfo,
    getUserInfo,
    clearUserInfo
  }
}, {
  persist: true,
})